// 导入 React 和 hooks
import React, { useState, useEffect } from 'react';
// 导入数据类型
import type { DataType } from '../../types/virtual list';
// 导入虚拟列表组件
import VirtualList from '../../components/VirtualList/VirtualList';
// 导入模拟数据
import { mockShopList } from '../../mock/shoplist';
// 导入样式
import './ShopingList.css';
// 导入 Ant Design 的组件
import { Pagination, Tooltip, Input, InputNumber, Space, Button, Modal, message } from 'antd';
import { SearchOutlined, DeleteOutlined } from '@ant-design/icons';
import request from '../../utils/request';

// 定义商品项类型
interface ShopItem {
  id: number;
  name: string;
  ingredients: string;
  price: number;
  effect: string;
  createdAt: string;
  image: string;
}

// 购物列表组件
const ShoppingList: React.FC = () => {
  // 原始的完整数据列表 (这里使用1000条模拟数据)
  const [fullData, setFullData] = useState<ShopItem[]>(mockShopList.list);
  // 当前页显示的数据
  const [currentPageData, setCurrentPageData] = useState<DataType[]>([]);
  // 当前页码
  const [currentPage, setCurrentPage] = useState(1);
  // 每页显示条数
  const [itemsPerPage, setItemsPerPage] = useState(10);
  // 搜索关键词
  const [searchTerm, setSearchTerm] = useState('');
  // 价格区间
  const [minPrice, setMinPrice] = useState<number | null>(null);
  const [maxPrice, setMaxPrice] = useState<number | null>(null);

  // 加载当前页数据
  useEffect(() => {
    // 根据搜索关键词和价格区间过滤数据
    const filteredData = fullData.filter(item => {
      const matchesName = item.name.toLowerCase().includes(searchTerm.toLowerCase());
      const matchesPrice = (
        (minPrice === null || item.price >= minPrice) &&
        (maxPrice === null || item.price <= maxPrice)
      );
      return matchesName && matchesPrice;
    });

    const indexOfLastItem = currentPage * itemsPerPage;
    const indexOfFirstItem = indexOfLastItem - itemsPerPage;
    const currentItems = filteredData.slice(indexOfFirstItem, indexOfLastItem);

    // Convert ShopItem to DataType, ensuring all required fields are present
    const formattedData = currentItems.map((item: ShopItem) => ({
      key: item.id,
      name: item.name || '', // Ensure name is string
      price: item.price || 0, // Ensure price is number
      stock: Math.floor(Math.random() * 100), // Simulate stock, ensure number
      ingredients: item.ingredients || '', // Ensure ingredients is string
      effect: item.effect || '', // Ensure effect is string
      image: item.image || '', // Ensure image is string
    })) as DataType[]; // Cast to DataType array
    setCurrentPageData(formattedData);
  }, [currentPage, itemsPerPage, fullData, searchTerm, minPrice, maxPrice]);

  // 处理搜索
  const handleSearch = (value: string) => {
    setSearchTerm(value);
    setCurrentPage(1); // 重置到第一页
  };

  // 处理价格区间变化
  const handlePriceChange = (type: 'min' | 'max', value: number | null) => {
    if (type === 'min') {
      setMinPrice(value);
    } else {
      setMaxPrice(value);
    }
    setCurrentPage(1); // 重置到第一页
  };

  // 处理行点击事件
  const handleRowClick = (item: DataType) => {
    console.log('点击了商品:', item);
  };

  // 处理页码或每页条数改变
  const handlePaginationChange = (page: number, pageSize?: number) => {
    setCurrentPage(page);
    if (pageSize) {
      setItemsPerPage(pageSize);
      // Reset to the first page when items per page changes
      if (pageSize !== itemsPerPage) {
          setCurrentPage(1);
      }
    }
  };

  // 处理删除操作
  const handleDelete = (item: DataType) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除商品"${item.name}"吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          const res = await request({
            url: `/api/shoplist/${item.key}`,
            method: 'delete',
          });
          if (res.code === 200) {
            message.success('删除成功');
            // 重新拉取数据并更新 fullData
            const listRes = await request({
              url: '/api/shoplist',
              method: 'get',
            });
            setFullData(listRes.data as ShopItem[]); // 类型断言，防止类型报错
          } else {
            message.error(res.message || '删除失败');
          }
        } catch {
          message.error('删除失败');
        }
      },
    });
  };

  // 自定义行渲染
  const renderItem = (item: DataType) => (
    <>
      <div className="cell image-cell">
        <img src={item.image} alt={item.name} style={{ width: '40px', height: '40px', objectFit: 'cover', borderRadius: '4px' }} />
      </div>
      <div className="cell">{item.name}</div>
      <div className="cell price-cell">¥{item.price?.toFixed(2)}</div>
      <div className="cell stock-cell">{item.stock}</div>
      <div className="cell">
        <Tooltip title={item.ingredients || ''}>
          <div style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {item.ingredients}
          </div>
        </Tooltip>
      </div>
      <div className="cell">
        <Tooltip title={item.effect || ''}>
          <div style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {item.effect}
          </div>
        </Tooltip>
      </div>
      <div className="cell">
        <Button
          type="text"
          danger
          icon={<DeleteOutlined />}
          onClick={(e: React.MouseEvent<HTMLElement>) => {
            e.stopPropagation();
            handleDelete(item);
          }}
        >
          删除
        </Button>
      </div>
    </>
  );

  // 自定义表头渲染
  const renderHeader = () => (
    <div className="header-row">
      <div className="cell">图片</div>
      <div className="cell">商品名称</div>
      <div className="cell">价格</div>
      <div className="cell">库存</div>
      <div className="cell">原材料</div>
      <div className="cell">功效</div>
      <div className="cell">操作</div>
    </div>
  );

  return (
    <div className="shopping-list-container">
      <h1 className="shopping-list-title">商品列表</h1>
      <div className="search-container">
        <Space>
          <Input
            placeholder="搜索商品名称"
            prefix={<SearchOutlined />}
            onChange={(e: React.ChangeEvent<HTMLInputElement>) => handleSearch(e.target.value)}
            style={{ width: '200px' }}
            allowClear
          />
          <InputNumber
            placeholder="最低价格"
            min={0}
            precision={2}
            onChange={(value: number | null) => handlePriceChange('min', value)}
            style={{ width: '120px' }}
            addonBefore="¥"
          />
          <span>-</span>
          <InputNumber
            placeholder="最高价格"
            min={0}
            precision={2}
            onChange={(value: number | null) => handlePriceChange('max', value)}
            style={{ width: '120px' }}
            addonBefore="¥"
          />
        </Space>
      </div>
      <div className="virtual-list-container">
        <div className="virtual-list-content">
          <VirtualList
            data={currentPageData}
            onRowClick={handleRowClick}
            containerHeight={window.innerHeight - 300}
            itemHeight={50}
            renderItem={renderItem}
            renderHeader={renderHeader}
          />
        </div>
      </div>
      <div className="pagination-container">
        <Pagination
          current={currentPage}
          pageSize={itemsPerPage}
          total={100000}
          onChange={handlePaginationChange}
          onShowSizeChange={handlePaginationChange}
          showSizeChanger
          pageSizeOptions={[10, 100, 500, 1000, 100000]}
        />
      </div>
    </div>
  );
};

export default ShoppingList;

